package com.chai.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.chai.dao.TravelGroupDao;
import com.chai.pojo.TravelGroup;
import com.chai.service.TravelGroupService;
import com.chai.vo.PageResult;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service(interfaceClass = TravelGroupService.class)
@Transactional
public class TravelGroupServiceImpl implements TravelGroupService {

    @Autowired
    TravelGroupDao travelGroupDao;

    @Override
    public void add(Integer[] travelItemIds, TravelGroup travelGroup) {
        travelGroupDao.add(travelGroup);

        //主键回填----
        Integer travelGroupId = travelGroup.getId();

        //往中间表插入关联数据
        setTravelGroupAndTravelItem(travelGroupId, travelItemIds);
    }


    private void setTravelGroupAndTravelItem(Integer travelGroupId, Integer[] travelItemIds) {
        if (travelItemIds != null && travelItemIds.length > 0) {
            for (Integer travelItemId : travelItemIds) {
                Map map = new HashMap();
                map.put("travelGroupId", travelGroupId);
                map.put("travelItemId", travelItemId);
                travelGroupDao.setTravelGroupAndTravelItem(map);
            }
        }
    }

    @Override
    public PageResult findPage(Integer currentPage, Integer pageSize, String queryString) {
        PageHelper.startPage(currentPage, pageSize);
        Page page = travelGroupDao.findPage(queryString);
        return new PageResult(page.getTotal(), page.getResult());
    }

    @Override
    public TravelGroup get(Integer id) {
        return travelGroupDao.get(id);
    }

    @Override
    public Integer[] getTravelItemIdsByTravelGroupId(Integer id) {
        return travelGroupDao.getTravelItemIdsByTravelGroupId(id);
    }

    @Override
    public void update(Integer[] travelItemIds, TravelGroup travelGroup) {
        travelGroupDao.update(travelGroup);

        //删除旧的关系数据
        travelGroupDao.delete(travelGroup.getId());

        //添加新的关系数据

        setTravelGroupAndTravelItem(travelGroup.getId(), travelItemIds);
    }

    @Override
    public void deleteTp(Integer id) {

        travelGroupDao.deleteTp(id);

    }

    @Override
    public List<TravelGroup> findAll() {
        return travelGroupDao.findAll();
    }
}
